package com.demo.wrapper.session.redis;

import com.demo.wrapper.session.SessionService;
import com.demo.common.utils.RedisKeyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**http://blog.csdn.net/fengshizty/article/details/50578639
 * SessionService实现session从redis的读写存储
 * 在redis的命令行用  keys "session:distributed:*"  可以查看到保存的所有sid,如下:

 127.0.0.1:6379> keys "session:distributed:*"
 1) "session:distributed:1efaaeaf-cb83-431d-874a-c31710446490"

 127.0.0.1:6379> get "session:distributed:1efaaeaf-cb83-431d-874a-c31710446490"
 "\xac\xed\x00\x05ur\x00\x02[B\xac\xf3\x17\xf8\x06\bT\xe0\x02\x00\x00xp\x00\x00\x00R\xac\xed\x00\x05sr\x00\x11java.util.HashMap\x05\a\xd
 a\xc1\xc3\x16`\xd1\x03\x00\x02F\x00\nloadFactorI\x00\tthresholdxp?@\x00\x00\x00\x00\x00\x00w\b\x00\x00\x00\x10\x00\x00\x00\x00x"

 查看过期的剩余时间:
 127.0.0.1:6379> TTL "session:distributed:1efaaeaf-cb83-431d-874a-c31710446490"
 (integer) 99

 */
@Component
@Order(1)
public class SessionServiceRedis implements SessionService {

    private final static Logger LOG = LoggerFactory.getLogger(SessionServiceRedis.class);

    private JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();

    private final RedisTemplate<Serializable, Serializable> redisTemplate;

    @Autowired
    public SessionServiceRedis(RedisTemplate<Serializable, Serializable> redisTemplate){
//        System.out.println("----初始化 SessionServiceRedis....");
        LOG.info("----初始化 SessionServiceRedis....redisTemplate = "+redisTemplate);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 从redis获取session数据
    * @param sid
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> getSession(String sid) {
        Map<String, Object> session = new HashMap<String, Object>();
        try {
            Object obj = redisTemplate.opsForValue()
                    .get(RedisKeyUtil.SESSION_DISTRIBUTED_SESSIONID + sid);
            if(obj != null){
                obj = jdkSerializer.deserialize((byte[])obj);
                session = (Map<String, Object>) obj;
            }
            LOG.info("从redis取出一个 obj = "+obj);
        } catch (Exception e) {
            LOG.error("Redis获取session异常" + e.getMessage(), e.getCause());
        }

        return session;
    }

    /**
     * 把session保存到redis
     * @param sid
     * @param session
     */
    @Override
    public void saveSession(String sid, Map<String, Object> session) {
        try {
            LOG.info("保存一个sid = "+sid +" , session = "+session);
            redisTemplate.opsForValue()
                    .set(RedisKeyUtil.SESSION_DISTRIBUTED_SESSIONID + sid,
                            jdkSerializer.serialize(session), RedisKeyUtil.SESSION_TIMEOUT,
                            TimeUnit.MINUTES);
        } catch (Exception e) {
            LOG.error("Redis保存session异常" + e.getMessage(), e.getCause());
        }
    }

    /**
     * delete session from redis
     * @param sid
     */
    @Override
    public void removeSession(String sid) {
        try {
            LOG.info("从redis删除一个sid = "+sid);
            redisTemplate.delete(
                    RedisKeyUtil.SESSION_DISTRIBUTED_SESSIONID + sid);
        } catch (Exception e) {
            LOG.error("Redis删除session异常" + e.getMessage(), e.getCause());
        }
    }
}
